package com.xuanyang.dormrepair.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xuanyang.dormrepair.model.entity.MFLink;
import com.xuanyang.dormrepair.model.entity.Maintainer;
import com.xuanyang.dormrepair.model.enums.MaintainerStatus;
import com.xuanyang.dormrepair.model.mapper.MFMapper;
import com.xuanyang.dormrepair.model.mapper.MaintainerMapper;
import com.xuanyang.dormrepair.utils.PageKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * @AUTHOR soft
 * @DATE 2019/5/19 12:11
 * @DESCRIBE 维修员
 */
@Slf4j
@Service
public class MaintainerService implements IService<Maintainer> {

    @Autowired
    private MaintainerMapper maintainerMapper;

    @Autowired
    private MFMapper mfMapper;

    @Transactional
    public boolean add(Maintainer maintainer) {
        maintainer.setDatetime(new Date())
                .setStatus(MaintainerStatus.ENABLE);
        if (maintainerMapper.insert(maintainer) > 0) {
            String[] fs = maintainer.getFs();
            if (fs != null) {
                for (String fno : fs) {
                    MFLink link = new MFLink().setFNo(fno).setMId(maintainer.getId());
                    mfMapper.insert(link);
                }
            }
            return true;
        }
        return false;
    }

    @Transactional
    public boolean delete(Serializable pk) {
        if (maintainerMapper.deleteById(pk) > 0) {
            mfMapper.deleteById(pk);
            return true;
        }
        return false;
    }

    @Transactional
    public boolean update(Maintainer maintainer) {
        if (maintainerMapper.updateById(maintainer) > 0) {
            String[] fs = maintainer.getFs();
            if (fs != null) {
                mfMapper.deleteById(maintainer.getId());
                for (String fno : fs) {
                    MFLink link = new MFLink().setFNo(fno).setMId(maintainer.getId());
                    mfMapper.insert(link);
                }
            }
            return true;
        }
        return false;
    }

    public Maintainer byId(Serializable pk) {
        return maintainerMapper.selectById(pk);
    }

    public IPage<Maintainer> page(int page, int limit, Maintainer query) {
        LambdaQueryWrapper<Maintainer> wrapper = Wrappers.lambdaQuery(query);
        wrapper.orderByDesc(Maintainer::getId);

        return maintainerMapper.selectPage(PageKit.of(page, limit), wrapper);
    }

    public List<Maintainer> listByHNo(String hno) {
        return maintainerMapper.listByHNo(hno);
    }
}
